/*
 * The thread Data Access Object, it handles all database transactions between the front end and the database.
 */

package airport.user.dao;
import java.util.List;

import airport.user.pojo.User;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.hibernate.HibernateException; 
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
//import org.hibernate.cfg.Configuration;


@SuppressWarnings("deprecation")
public class UserDAO {
	
	private static SessionFactory factory = new AnnotationConfiguration().configure().addAnnotatedClass(User.class).addPackage("com.xyz").buildSessionFactory(); 
	
	//adds the given user to the database
	public void addUser(User user) {
		 try {
			 //System.out.println("build Factory");
			 //System.out.println("open Session");
	         Session session = factory.openSession();
	         Transaction tx = null;
	         try {
	        	 tx = session.beginTransaction();
	        	 session.save(user); 
	        	 tx.commit();
	        	 } 
	         catch (HibernateException e) {
	        	 if (tx!=null) 
	        		 tx.rollback();
	        	 e.printStackTrace(); 
	         } 
	         finally {
	            session.close(); 
	         }
	      } catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex); 
	      }
	}
	
	//updates a user's password in the database
	public void updatePassword(String username, String newPassword) {
		try {
	         Session session = factory.openSession();
	         Transaction tx = null;
	         try {
	        	 tx = session.beginTransaction();
	        	 //code goes here
	        	 String hql = "UPDATE User set password = '" +newPassword+ 
             "' WHERE user_name = '" +username+"'";
	        	 Query query = session.createQuery(hql);
	        	 int result = query.executeUpdate();
	        	 tx.commit();
	        	 System.out.println("Rows affected: " + result);
	         } catch (HibernateException e) {
	        	 if (tx!=null) 
	        		 tx.rollback();
	        	 e.printStackTrace(); 
	         } 
	         finally {
	            session.close(); 
	         }
	         
		} catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex); 
	      }
	}
	
	//updates the user's email in the database
	public void updateEmail(String username, String newEmail) {
		try {
	         Session session = factory.openSession();
	         Transaction tx = null;
	         try {
	        	 tx = session.beginTransaction();
	        	 //code goes here
	        	 String hql = "UPDATE User set email = '" +newEmail+ 
             "' WHERE user_name = '" +username+"'";
	        	 Query query = session.createQuery(hql);
	        	 int result = query.executeUpdate();
	        	 tx.commit();
	        	 System.out.println("Rows affected: " + result);
	         } catch (HibernateException e) {
	        	 if (tx!=null) 
	        		 tx.rollback();
	        	 e.printStackTrace(); 
	         } 
	         finally {
	            session.close(); 
	         }
	         
		} catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex); 
	      }
	}
	
	//returns the user with the email specified, used for logins
	@SuppressWarnings("unchecked")
	public User findUserByEmail(String email) {
		
		User user = null;
		 try {
			 //System.out.println("build Factory");
			 //System.out.println("open Session");
	         Session session = factory.openSession();
	         try {
	        	 System.out.println("start query");
	        	 String hql = "FROM User U where U.email = '"+email+"'";
	        	 System.out.println(hql);
	        	 Query query = session.createQuery(hql);
	        	 List<User> results = query.list();
	        	 System.out.println("user:"+results.size());
	        	 if (results.size() != 0) {
	        		 user = results.get(0);
	        		 System.out.println("user found!"); 
	        	 	}
	        	 else
	        	 	System.out.println("no user found");
	        	 
	        	 } 
	         catch (HibernateException e) {
	        	 e.printStackTrace();
	         } 
	         finally {
	            session.close(); 
	         }
	      } catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex);
	      }
		 return user;	
	}
	
	//gets the user's password using the given email, used for changing
	@SuppressWarnings("unchecked")
	public String findPasswordByEmail(String email) {
		String password = null;
		try {
			 System.out.println("build Factory");
			 System.out.println("open Session");
	         Session session = factory.openSession();
	         try {
	        	 //System.out.println("start query");
	        	 String hql = "SELECT U.password FROM User U where U.email = '"+email+"'";
	        	 //System.out.println(hql);
	        	 Query query = session.createQuery(hql);
	        	 System.out.println("query");
	        	 List<String> results = query.list();
	        	 System.out.println("size:"+results.size());
	        	 if ((results != null)&&(results.size()!=0))
	        		 password = results.get(0);
	        	 //System.out.println("user found!");
	        	 } 
	         catch (HibernateException e) {
	        	 e.printStackTrace();
	         } 
	         finally {
	            session.close(); 
	         }
	      } catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex);
	      }
		return password;
	}
	
	
	//retrieves a string containing the username associated with the email
	@SuppressWarnings("unchecked")
	public String findUsernameByEmail(String email) {
		String username = null;
		try {
			 System.out.println("build Factory");
			 System.out.println("open Session");
	         Session session = factory.openSession();
	         try {
	        	 //System.out.println("start query");
	        	 String hql = "SELECT U.userName FROM User U where U.email = '"+email+"'";
	        	 //System.out.println(hql);
	        	 Query query = session.createQuery(hql);
	        	 List<String> results = query.list();
	        	 
	        	 System.out.println("WHATTHEHECK DOOD: " + results);
	        	 if (results != null)
	        		 username = results.get(0);
	        	 //System.out.println("user found!");
	        	 } 
	         catch (HibernateException e) {
	        	 e.printStackTrace();
	         } 
	         finally {
	            session.close(); 
	         }
	      } catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex);
	      }
		return username;
	}
	
	//retrieves a user using the username, commonly found in the cookie
	@SuppressWarnings("unchecked")
	public User findUserByUserName(String username) {
		
		User user = null;
		 try {
			 //System.out.println("build Factory");
			 //System.out.println("open Session");
	         Session session = factory.openSession();
	         try {
	        	 System.out.println("start find user by username");
	        	 String hql = "FROM User U where U.userName = '"+username+"'";
	        	 System.out.println(hql);
	        	 Query query = session.createQuery(hql);
	        	 System.out.println("here--->");
	        	 if (query.list().size() == 0) {
	        		 System.out.println("the size is 0 ------>>>");
	        	 }
	        	 else
	        	 {
	        		 List<User> results = query.list();
		        	 System.out.println("WHATTHEHECK DOOD: " + results);
		        	 if (results != null) {
		        		 user = results.get(0);
		        		 System.out.println("user found!");
		        	 }
	        	 }
	        	 
	        	 //
	        	 } 
	         catch (HibernateException e) {
	        	 e.printStackTrace();
	         } 
	         finally {
	            session.close(); 
	         }
	      } catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex);
	      }
		 return user;	
	}
	
	//updates user's image
	public void updateAvatar(String avatar, String username) {
		try {
	         Session session = factory.openSession();
	         Transaction tx = null;
	         try {
	        	 System.out.println("updating avatar");
	        	 tx = session.beginTransaction();
	        	 //System.out.println("0");
	        	 /*User user = findUserByUserName(username);
	        	 long id = user.getId();
	        	 user =  (User)session.get(User.class, id);*/
	        	 String hql = "UPDATE User set avatar = '" +avatar+ 
	                     "' WHERE user_name = '" +username+"'";
	        	 Query query = session.createQuery(hql);
	        	 int result = query.executeUpdate();
	        	 System.out.println("Rows affected: " + result);
	        	 tx.commit();
	        	 } 
	         catch (HibernateException e) {
	        	 if (tx!=null) 
	        		 tx.rollback();
	        	 e.printStackTrace(); 
	         } 
	         finally {
	            session.close(); 
	         }
	      } catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex); 
	      }
	}

	//updates profile information associated with the given user
	public void updateProfile (String gender, String occupation, String travelReason, String age, String username) {
		try {
	         Session session = factory.openSession();
	         Transaction tx = null;
	         try {
	        	 System.out.println("updating profile");
	        	 tx = session.beginTransaction();
	        	 //long id = findUserIdByUserName(username);
	        	 /*System.out.println("0");
	        	 User user = findUserByUserName(username);
	        	 System.out.println("1");
	        	 System.out.println("User ID:"+user.getId());
	        	 System.out.println("2");
	        	 long id = user.getId();
	        	 //User user =  (User)session.get(User.class, id);
	        	 //System.out.println("1");
	        	 if (gender!= null)
	        		 user.setGender(gender);
		         if (occupation!=null) 
		        	 user.setOccupation(occupation);
		         if (travelReason!=null)
		        	 user.setTravelReason(travelReason);
		         if (birthday!=null)
		        	 user.setBirthday(birthday);
		         session.update(user);*/
	        	 if (gender!= null) {
	        		 String hql = "UPDATE User set gender = '" +gender+ 
		                     "' WHERE user_name = '" +username+"'";
		        	 Query query = session.createQuery(hql);
		        	 int result = query.executeUpdate();
		        	 System.out.println("Rows affected: " + result);
	        	 }
		         if (occupation!=null) {
		        	 String hql = "UPDATE User set occupation = '" +occupation+ 
		                     "' WHERE user_name = '" +username+"'";
		        	 Query query = session.createQuery(hql);
		        	 int result = query.executeUpdate();
		        	 System.out.println("Rows affected: " + result);
		         }
		         if (travelReason!=null) {
		        	 String hql = "UPDATE User set travel_reason = '" +travelReason+ 
		                     "' WHERE user_name = '" +username+"'";
		        	 Query query = session.createQuery(hql);
		        	 int result = query.executeUpdate();
		        	 System.out.println("Rows affected: " + result);
		         }
		         if (age!= null) {
		        	 String hql = "UPDATE User set age = '" +age+ 
		                     "' WHERE user_name = '" +username+"'";
		        	 Query query = session.createQuery(hql);
		        	 int result = query.executeUpdate();
		        	 System.out.println("Rows affected: " + result);
		         }
	        	 tx.commit();
	        	 } 
	         catch (HibernateException e) {
	        	 if (tx!=null) 
	        		 tx.rollback();
	        	 e.printStackTrace(); 
	         } 
	         finally {
	            session.close(); 
	         }
	      } catch (Throwable ex) { 
	         System.err.println("Failed to create sessionFactory object." + ex);
	         throw new ExceptionInInitializerError(ex); 
	      }
		
	}
	
}
